package com.king.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 聊天室-服务端
 *
 * @author king
 * @date 2020/12/29 23:17
 */
public class GroupChatServer {

    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    /**
     * 初始化工作
     */
    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // ServerSockerChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置非阻塞
            listenChannel.configureBlocking(false);
            // 将该 listenChannel 注册到 selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     */
    public void listen() {
        try {
            // 循环处理
            while (true) {
                // 监听
//                int select = selector.select(2000);
                int select = selector.select();

                // 有事件
                if (select > 0) {
                    // 遍历得到 selectionKey 集合
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();

                    while (selectionKeyIterator.hasNext()) {
                        // 取出 selectionKey
                        SelectionKey selectionKey = selectionKeyIterator.next();

                        // 监听到 ACCEPT
                        if (selectionKey.isAcceptable()) {
                            // 将 socketChannel 注册到 selector
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);

                            // 给出提示
                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }

                        // 监听到 READ
                        if (selectionKey.isReadable()) {
                            // 处理读
                            readData(selectionKey);
                        }
                        selectionKeyIterator.remove();
                    }
                } else {
                    // 没有事件
                    System.out.println("等待。。。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端消息
     *
     * @param key selectionKey
     */
    private void readData(SelectionKey key) {
        // 渠道关联的channel
        SocketChannel channel = null;
        try {
            // 得到 channel
            channel = (SocketChannel) key.channel();
            // 创建 buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);

            // 根据 count 的值做处理
            if (count > 0) {
                // 把缓存区的数据转成字符串
                String msg = new String(buffer.array());

                // 输出该消息
                System.out.println("from 客户端：" + msg);

                // 向其他的客户端转发消息
                sendInfoToOtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了。。。");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 转发消息给其它客户端（通道）
     *
     * @param msg
     * @param self
     */
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中。。。");

        // 遍历所有注册到 selector 上的 SocketChannel，并排除自己
        Set<SelectionKey> selectionKeys = selector.keys();

        // 通过 key 去除对应的 socketChannel
        for (SelectionKey selectionKey : selectionKeys) {
            // 排除自己
            Channel channel = selectionKey.channel();
            if (channel instanceof SocketChannel && channel != self) {
                // 转型
                SocketChannel socketChannel = (SocketChannel) channel;

                // 将 msg 存储到 buffer
                socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
            }
        }
    }

    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();

        groupChatServer.listen();

    }
}
